using System.Windows.Forms;
using TeachingManagementSystem.BLL;
using TeachingManagementSystem.Models;

namespace TeachingManagementSystem.Forms.ScheduleManagement
{
    public partial class ScheduleListForm : Form
    {
        private ScheduleBLL _scheduleBLL;
        private CourseBLL _courseBLL;
        private ClassroomBLL _classroomBLL;
        private UserBLL _userBLL;
        private User _currentUser;

        public ScheduleListForm(User currentUser)
        {
            InitializeComponent();
            _scheduleBLL = new ScheduleBLL();
            _courseBLL = new CourseBLL();
            _classroomBLL = new ClassroomBLL();
            _userBLL = new UserBLL();
            _currentUser = currentUser;
            InitializeDataGridView();
            LoadSchedules();
            SetupFilters();
            SetupRolePermissions();
            
            // 设置为合适的窗口大小
            this.WindowState = FormWindowState.Normal;
            this.Size = new System.Drawing.Size(1000, 700);
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void SetupRolePermissions()
        {
            // 根据用户角色设置不同的权限
            if (_currentUser.Role == UserRole.Student)
            {
                // 学生只能查看课表，不能修改
                btnAdd.Enabled = false;
                btnEdit.Enabled = false;
                btnDelete.Enabled = false;
                this.Text = "查询课表";
            }
            else if (_currentUser.Role != UserRole.Administrator && _currentUser.Role != UserRole.Staff && _currentUser.Role != UserRole.Teacher)
            {
                // 其他非授权角色禁用管理功能
                btnAdd.Enabled = false;
                btnEdit.Enabled = false;
                btnDelete.Enabled = false;
            }
            else if (_currentUser.Role == UserRole.Teacher)
            {
                // 教师可以进行排课和调整课表
                btnAdd.Enabled = true;
                btnEdit.Enabled = true;
                // 可以根据需要决定是否允许教师删除课表
                btnDelete.Enabled = true;
                this.Text = "排课管理";
            }
        }

        private void InitializeDataGridView()
        {
            // 设置DataGridView列
            dataGridViewSchedules.AutoGenerateColumns = false;
            dataGridViewSchedules.Columns.AddRange(new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn { HeaderText = "课表ID", DataPropertyName = "ScheduleID" },
                new DataGridViewTextBoxColumn { HeaderText = "课程名称", Name = "CourseName", DataPropertyName = "CourseName" },
                new DataGridViewTextBoxColumn { HeaderText = "教师姓名", Name = "TeacherName", DataPropertyName = "TeacherName" },
                new DataGridViewTextBoxColumn { HeaderText = "教室", Name = "ClassroomNumber", DataPropertyName = "ClassroomNumber" },
                new DataGridViewTextBoxColumn { HeaderText = "星期", DataPropertyName = "DayOfWeek" },
                new DataGridViewTextBoxColumn { HeaderText = "开始节次", DataPropertyName = "StartSection" },
                new DataGridViewTextBoxColumn { HeaderText = "节数", DataPropertyName = "SectionCount" },
                new DataGridViewTextBoxColumn { HeaderText = "学期", DataPropertyName = "Semester" }
            });

            // 设置DataGridView属性
            dataGridViewSchedules.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridViewSchedules.MultiSelect = false;
        }

        private void SetupFilters()
        {
            // 加载学期选项
            comboBoxSemesterFilter.Items.AddRange(new string[] { "全部学期", "2024-2025学年第一学期", "2024-2025学年第二学期", 
                "2023-2024学年第一学期", "2023-2024学年第二学期" });
            // 安全设置选中项，确保不产生null警告
            comboBoxSemesterFilter.SelectedItem = "全部学期";

            // 加载星期选项
            comboBoxDayFilter.Items.AddRange(new string[] { "全部星期", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" });
            comboBoxDayFilter.SelectedItem = "全部星期";

            // 根据用户角色加载筛选选项
            if (_currentUser.Role == UserRole.Teacher)
            {
                // 教师只能看到自己的课表
                comboBoxTeacherFilter.Items.Add($"{_currentUser.FullName} (ID:{_currentUser.UserID})");
                comboBoxTeacherFilter.SelectedIndex = 0;
                comboBoxTeacherFilter.Enabled = false;
            }
            else
            {
                // 加载所有教师
                var teachers = _userBLL.GetUsersByRole(UserRole.Teacher);
                comboBoxTeacherFilter.Items.Add("全部教师");
                foreach (var teacher in teachers)
                {
                    comboBoxTeacherFilter.Items.Add($"{teacher.FullName} (ID:{teacher.UserID})");
                }
                comboBoxTeacherFilter.SelectedItem = "全部教师";
            }

            // 加载所有课程
            comboBoxCourseFilter.Items.Add("全部课程");
            var courses = _courseBLL.GetAllCourses();
            foreach (var course in courses)
            {
                comboBoxCourseFilter.Items.Add($"{course.CourseName} ({course.CourseCode})");
            }
            comboBoxCourseFilter.SelectedItem = "全部课程";
        }

        private void LoadSchedules()
        {
            try
            {
                // 确保BLL实例不为null
                if (_scheduleBLL == null || _courseBLL == null || _userBLL == null || _classroomBLL == null)
                {
                    MessageBox.Show("系统初始化失败，请重新启动应用程序。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var schedules = _scheduleBLL.GetAllSchedules();
                
                // 检查schedules是否为null
                if (schedules == null)
                {
                    dataGridViewSchedules.DataSource = null;
                    return;
                }
                
                // 根据用户角色过滤
                if (_currentUser != null && _currentUser.Role == UserRole.Teacher)
                {
                    schedules = schedules.Where(s => s.TeacherID == _currentUser.UserID).ToList();
                }
                else if (_currentUser != null && _currentUser.Role == UserRole.Student)
                {
                    // 学生视图可以在这里添加
                    // 暂时显示所有课程
                }

                // 转换为显示模型
                var displayData = new List<object>();
                foreach (var s in schedules)
                {
                    string courseName = "未找到课程";
                    string teacherName = "未找到教师";
                    string classroomNumber = "未找到教室";

                    if (_courseBLL != null && s.CourseID > 0)
                    {
                        var course = _courseBLL.GetCourseByID(s.CourseID);
                        if (course != null)
                            courseName = course.CourseName ?? string.Empty;
                    }

                    if (_userBLL != null && s.TeacherID > 0)
                    {
                        var teacher = _userBLL.GetUserByID(s.TeacherID);
                        if (teacher != null)
                            teacherName = teacher.FullName ?? string.Empty;
                    }

                    if (_classroomBLL != null && s.ClassroomID > 0)
                    {
                        var classroom = _classroomBLL.GetClassroomByID(s.ClassroomID);
                        if (classroom != null)
                            classroomNumber = classroom.ClassroomNumber ?? string.Empty;
                    }

                    // 转换DayOfWeek枚举为中文星期名称
                    string chineseDayOfWeek = "星期一"; // 默认值
                    switch (s.DayOfWeek)
                    {
                        case DayOfWeek.Monday:
                            chineseDayOfWeek = "星期一";
                            break;
                        case DayOfWeek.Tuesday:
                            chineseDayOfWeek = "星期二";
                            break;
                        case DayOfWeek.Wednesday:
                            chineseDayOfWeek = "星期三";
                            break;
                        case DayOfWeek.Thursday:
                            chineseDayOfWeek = "星期四";
                            break;
                        case DayOfWeek.Friday:
                            chineseDayOfWeek = "星期五";
                            break;
                        case DayOfWeek.Saturday:
                            chineseDayOfWeek = "星期六";
                            break;
                        case DayOfWeek.Sunday:
                            chineseDayOfWeek = "星期日";
                            break;
                    }

                    displayData.Add(new
                    {
                        s.ScheduleID,
                        CourseName = courseName,
                        TeacherName = teacherName,
                        ClassroomNumber = classroomNumber,
                        DayOfWeek = chineseDayOfWeek,
                        StartSection = s.StartSection,
                        SectionCount = s.SectionCount,
                        Semester = s.Semester ?? ""
                    });
                }

                dataGridViewSchedules.DataSource = displayData;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载课表数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitializeComponent()
        {
            this.dataGridViewSchedules = new System.Windows.Forms.DataGridView();
            this.btnAdd = new System.Windows.Forms.Button();
            this.btnEdit = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnRefresh = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.comboBoxSemesterFilter = new System.Windows.Forms.ComboBox();
            this.comboBoxDayFilter = new System.Windows.Forms.ComboBox();
            this.comboBoxCourseFilter = new System.Windows.Forms.ComboBox();
            this.comboBoxTeacherFilter = new System.Windows.Forms.ComboBox();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewSchedules)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGridViewSchedules
            // 
            this.dataGridViewSchedules.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGridViewSchedules.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridViewSchedules.Location = new System.Drawing.Point(12, 100);
            this.dataGridViewSchedules.Name = "dataGridViewSchedules";
            this.dataGridViewSchedules.RowHeadersWidth = 51;
            this.dataGridViewSchedules.RowTemplate.Height = 27;
            this.dataGridViewSchedules.Size = new System.Drawing.Size(876, 300);
            this.dataGridViewSchedules.TabIndex = 0;
            // 
            // btnAdd
            // 
            this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.btnAdd.Location = new System.Drawing.Point(12, 420);
            this.btnAdd.Name = "btnAdd";
            this.btnAdd.Size = new System.Drawing.Size(80, 30);
            this.btnAdd.TabIndex = 1;
            this.btnAdd.Text = "添加";
            this.btnAdd.UseVisualStyleBackColor = true;
            this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
            // 
            // btnEdit
            // 
            this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.btnEdit.Location = new System.Drawing.Point(100, 420);
            this.btnEdit.Name = "btnEdit";
            this.btnEdit.Size = new System.Drawing.Size(80, 30);
            this.btnEdit.TabIndex = 2;
            this.btnEdit.Text = "编辑";
            this.btnEdit.UseVisualStyleBackColor = true;
            this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
            // 
            // btnDelete
            // 
            this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.btnDelete.Location = new System.Drawing.Point(188, 420);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(80, 30);
            this.btnDelete.TabIndex = 3;
            this.btnDelete.Text = "删除";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // btnRefresh
            // 
            this.btnRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnRefresh.Location = new System.Drawing.Point(808, 420);
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.Size = new System.Drawing.Size(80, 30);
            this.btnRefresh.TabIndex = 4;
            this.btnRefresh.Text = "刷新";
            this.btnRefresh.UseVisualStyleBackColor = true;
            this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
            this.btnRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 20);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(52, 15);
            this.label1.TabIndex = 5;
            this.label1.Text = "学期:";
            this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(250, 20);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(52, 15);
            this.label2.TabIndex = 6;
            this.label2.Text = "星期:";
            this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(12, 60);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(52, 15);
            this.label3.TabIndex = 7;
            this.label3.Text = "课程:";
            this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(250, 60);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(52, 15);
            this.label4.TabIndex = 8;
            this.label4.Text = "教师:";
            this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)));
            // 
            // comboBoxSemesterFilter
            // 
            this.comboBoxSemesterFilter.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.comboBoxSemesterFilter.FormattingEnabled = true;
            this.comboBoxSemesterFilter.Location = new System.Drawing.Point(70, 17);
            this.comboBoxSemesterFilter.Name = "comboBoxSemesterFilter";
            this.comboBoxSemesterFilter.Size = new System.Drawing.Size(170, 23);
            this.comboBoxSemesterFilter.TabIndex = 9;
            this.comboBoxSemesterFilter.SelectedIndexChanged += new System.EventHandler(this.FilterChanged);
            // 
            // comboBoxDayFilter
            // 
            this.comboBoxDayFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.comboBoxDayFilter.FormattingEnabled = true;
            this.comboBoxDayFilter.Location = new System.Drawing.Point(308, 17);
            this.comboBoxDayFilter.Name = "comboBoxDayFilter";
            this.comboBoxDayFilter.Size = new System.Drawing.Size(120, 23);
            this.comboBoxDayFilter.TabIndex = 10;
            this.comboBoxDayFilter.SelectedIndexChanged += new System.EventHandler(this.FilterChanged);
            // 
            // comboBoxCourseFilter
            // 
            this.comboBoxCourseFilter.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.comboBoxCourseFilter.FormattingEnabled = true;
            this.comboBoxCourseFilter.Location = new System.Drawing.Point(70, 57);
            this.comboBoxCourseFilter.Name = "comboBoxCourseFilter";
            this.comboBoxCourseFilter.Size = new System.Drawing.Size(170, 23);
            this.comboBoxCourseFilter.TabIndex = 11;
            this.comboBoxCourseFilter.SelectedIndexChanged += new System.EventHandler(this.FilterChanged);
            // 
            // comboBoxTeacherFilter
            // 
            this.comboBoxTeacherFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.comboBoxTeacherFilter.FormattingEnabled = true;
            this.comboBoxTeacherFilter.Location = new System.Drawing.Point(308, 57);
            this.comboBoxTeacherFilter.Name = "comboBoxTeacherFilter";
            this.comboBoxTeacherFilter.Size = new System.Drawing.Size(170, 23);
            this.comboBoxTeacherFilter.TabIndex = 12;
            this.comboBoxTeacherFilter.SelectedIndexChanged += new System.EventHandler(this.FilterChanged);
            // 
            // ScheduleListForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(900, 470);
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.Controls.Add(this.comboBoxTeacherFilter);
            this.Controls.Add(this.comboBoxCourseFilter);
            this.Controls.Add(this.comboBoxDayFilter);
            this.Controls.Add(this.comboBoxSemesterFilter);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.btnRefresh);
            this.Controls.Add(this.btnDelete);
            this.Controls.Add(this.btnEdit);
            this.Controls.Add(this.btnAdd);
            this.Controls.Add(this.dataGridViewSchedules);
            this.Name = "ScheduleListForm";
            this.Text = "课表管理";
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewSchedules)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        private void btnAdd_Click(object? sender, EventArgs e)
        {
            // 创建一个新的Schedule对象而不是传递null
            ScheduleEditForm form = new ScheduleEditForm(new Schedule(), _currentUser);
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadSchedules();
            }
        }

        private void btnEdit_Click(object? sender, EventArgs e)
        {
            if (dataGridViewSchedules.SelectedRows.Count > 0)
            {
                var selectedRow = dataGridViewSchedules.SelectedRows[0];
                if (selectedRow != null && selectedRow.DataBoundItem != null)
                {
                    // 使用动态类型或反射获取ScheduleID
                    try
                    {
                        dynamic dataItem = selectedRow.DataBoundItem;
                        int scheduleID = dataItem.ScheduleID;
                        
                        Schedule? schedule = _scheduleBLL?.GetScheduleByID(scheduleID);
                        if (schedule != null && _currentUser != null)
                        {
                            ScheduleEditForm form = new ScheduleEditForm(schedule, _currentUser);
                            if (form.ShowDialog() == DialogResult.OK)
                            {
                                LoadSchedules();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 如果动态类型失败，尝试通过索引访问
                        try
                        {
                            // 假设ScheduleID是第一列
                            if (selectedRow.Cells.Count > 0 && selectedRow.Cells[0].Value != null)
                            {
                                string idStr = selectedRow.Cells[0].Value.ToString();
                                if (int.TryParse(idStr, out int scheduleID))
                                {
                                    Schedule? schedule = _scheduleBLL?.GetScheduleByID(scheduleID);
                                    if (schedule != null && _currentUser != null)
                                    {
                                        ScheduleEditForm form = new ScheduleEditForm(schedule, _currentUser);
                                        if (form.ShowDialog() == DialogResult.OK)
                                        {
                                            LoadSchedules();
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("无法获取课表ID", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择要编辑的课表", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnDelete_Click(object? sender, EventArgs e)
        {
            if (dataGridViewSchedules.SelectedRows.Count > 0)
            {
                var selectedRow = dataGridViewSchedules.SelectedRows[0];
                if (selectedRow != null && selectedRow.DataBoundItem != null)
                {
                    // 使用动态类型或反射获取ScheduleID
                    try
                    {
                        dynamic dataItem = selectedRow.DataBoundItem;
                        int scheduleID = dataItem.ScheduleID;
                        
                        if (MessageBox.Show("确定要删除选中的课表吗？", "确认", 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            try
                            {
                                if (_scheduleBLL != null)
                                {
                                    _scheduleBLL.DeleteSchedule(scheduleID);
                                    LoadSchedules();
                                    MessageBox.Show("课表已删除", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"删除课表时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // 如果动态类型失败，尝试通过索引访问
                        try
                        {
                            // 假设ScheduleID是第一列
                            if (selectedRow.Cells.Count > 0 && selectedRow.Cells[0].Value != null)
                            {
                                object cellValue = selectedRow.Cells[0].Value;
                                if (cellValue != null && int.TryParse(cellValue.ToString(), out int scheduleID))
                                {
                                    if (MessageBox.Show("确定要删除选中的课表吗？", "确认", 
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                                    {
                                        try
                                        {
                                            if (_scheduleBLL != null)
                                            {
                                                _scheduleBLL.DeleteSchedule(scheduleID);
                                                LoadSchedules();
                                                MessageBox.Show("课表已删除", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            MessageBox.Show($"删除课表时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("无法获取课表ID", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("无法获取课表信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("请选择要删除的课表", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnRefresh_Click(object? sender, EventArgs e)
        {
            LoadSchedules();
        }

        // 使用nullable reference类型的参数来匹配EventHandler委托
        private void FilterChanged(object? sender, EventArgs e)
        {
            ApplyFilters();
        }

        private void ApplyFilters()
        {
            try
            {
                // 确保BLL实例不为null
                if (_scheduleBLL == null || _courseBLL == null || _userBLL == null || _classroomBLL == null)
                {
                    MessageBox.Show("系统初始化失败，请重新启动应用程序。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 安全获取ComboBox选中项
                string semester = comboBoxSemesterFilter.SelectedItem?.ToString() ?? "全部学期";
                string day = comboBoxDayFilter.SelectedItem?.ToString() ?? "全部星期";
                string courseText = comboBoxCourseFilter.SelectedItem?.ToString() ?? "全部课程";
                string teacherText = comboBoxTeacherFilter.SelectedItem?.ToString() ?? "全部教师";

                var schedules = _scheduleBLL.GetAllSchedules();

                // 检查schedules是否为null
                if (schedules == null)
                {
                    dataGridViewSchedules.DataSource = null;
                    return;
                }

                // 根据用户角色过滤
                if (_currentUser != null && _currentUser.Role == UserRole.Teacher)
                {
                    schedules = schedules.Where(s => s.TeacherID == _currentUser.UserID).ToList();
                }

                // 应用学期过滤
                if (!string.IsNullOrEmpty(semester) && semester != "全部学期")
                {
                    schedules = schedules.Where(s => s.Semester == semester).ToList();
                }

                // 应用星期过滤
                if (!string.IsNullOrEmpty(day) && day != "全部星期")
                {
                    schedules = schedules.Where(s => s.DayOfWeek.ToString() == day).ToList();
                }

                // 应用课程过滤
                if (!string.IsNullOrEmpty(courseText) && courseText != "全部课程")
                {
                    // 从文本中提取课程信息并过滤
                    var course = _courseBLL.GetAllCourses()?.FirstOrDefault(c => 
                        c != null && !string.IsNullOrEmpty(c.CourseName) && !string.IsNullOrEmpty(c.CourseCode) && 
                        courseText.Contains(c.CourseName) && courseText.Contains(c.CourseCode));
                    if (course != null)
                    {
                        schedules = schedules.Where(s => s.CourseID == course.CourseID).ToList();
                    }
                }

                // 应用教师过滤
                if (!string.IsNullOrEmpty(teacherText) && teacherText != "全部教师" && 
                    _currentUser != null && _currentUser.Role != UserRole.Teacher)
                {
                    // 从文本中提取教师ID
                    if (teacherText.Contains("ID:"))
                    {
                        int startIndex = teacherText.LastIndexOf("ID:") + 3;
                        int endIndex = teacherText.LastIndexOf(")");
                        if (startIndex > 0 && endIndex > startIndex && endIndex <= teacherText.Length)
                        {
                            string idText = teacherText.Substring(startIndex, endIndex - startIndex);
                            if (int.TryParse(idText, out int teacherID))
                            {
                                schedules = schedules.Where(s => s.TeacherID == teacherID).ToList();
                            }
                        }
                    }
                }

                // 转换为显示模型
                var displayData = new List<object>();
                foreach (var s in schedules)
                {
                    string courseName = "未找到课程";
                    string teacherName = "未找到教师";
                    string classroomNumber = "未找到教室";

                    if (_courseBLL != null && s.CourseID > 0)
                    {
                        var course = _courseBLL.GetCourseByID(s.CourseID);
                        if (course != null)
                            courseName = course.CourseName ?? string.Empty;
                    }

                    if (_userBLL != null && s.TeacherID > 0)
                    {
                        var teacher = _userBLL.GetUserByID(s.TeacherID);
                        if (teacher != null)
                            teacherName = teacher.FullName ?? string.Empty;
                    }

                    if (_classroomBLL != null && s.ClassroomID > 0)
                    {
                        var classroom = _classroomBLL.GetClassroomByID(s.ClassroomID);
                        if (classroom != null)
                            classroomNumber = classroom.ClassroomNumber ?? string.Empty;
                    }

                    displayData.Add(new
                    {
                        s.ScheduleID,
                        CourseName = courseName,
                        TeacherName = teacherName,
                        ClassroomNumber = classroomNumber,
                        DayOfWeek = s.DayOfWeek,
                        StartSection = s.StartSection,
                        SectionCount = s.SectionCount,
                        Semester = s.Semester ?? ""
                    });
                }

                dataGridViewSchedules.DataSource = displayData;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"应用筛选条件时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private System.Windows.Forms.DataGridView dataGridViewSchedules;
        private System.Windows.Forms.Button btnAdd;
        private System.Windows.Forms.Button btnEdit;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnRefresh;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.ComboBox comboBoxSemesterFilter;
        private System.Windows.Forms.ComboBox comboBoxDayFilter;
        private System.Windows.Forms.ComboBox comboBoxCourseFilter;
        private System.Windows.Forms.ComboBox comboBoxTeacherFilter;
    }
}